import { ObjDecoder, ObjEncoder } from "k-coder";
import Protocol, { PROTO_STRUCT } from "../out/protocol/Protocol"

/** 协议派发器 */
export default class ProtoDispatcher {

    private _callbackMap: Map<Protocol, { caller: any, callback: (data: any) => void }> = new Map()

    /** 接收消息 */
    onMsg(bytes: Uint8Array) {
        console.log(bytes);

        let protocol: Protocol
        let data = ObjDecoder.decodeDeal(bytes, r => {
            //读取协议号
            protocol = r.uint
            return PROTO_STRUCT[protocol]
        })

        let cb = this._callbackMap.get(protocol)
        cb?.callback.call(cb.caller, data)
    }

    /** 监听协议 */
    on<VO>(protocol: Protocol, caller: any, callback: (data: VO) => void) {
        this._callbackMap.set(protocol, { caller, callback })
    }

    /** 协议vo转换为二进制数据 */
    from<VO>(protocol: Protocol, data: VO) {
        let bytes = ObjEncoder.encodeDeal(data, PROTO_STRUCT[protocol], w => {
            //开头写入协议号
            w.uint = protocol
        })
        return bytes
    }
}